/*
 * @Author: silence
 * @Date: 2022-07-26 16:15:12
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-12-14 20:03:37
 * @Description: 网络参数拦截器：处理公共参数
 */

import 'package:dio/dio.dart';
import 'package:ems_neutral_app/config/AppInfo.dart';
import '../../../bloc/userbloc/user_bloc.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../pages/Mine/Language/LanguageController.dart';
import '../pages/Mine/Language/SilLocalizations/SilLocalizations.dart';

class NetParamInterceptor implements Interceptor {
  // 是否需要处理参数，默认需要处理
  final bool isNeedHandler;
  // 是否是表单
  final bool isFormData;
  const NetParamInterceptor(
      {this.isNeedHandler = true, this.isFormData = false});

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    handler.next(err);
  }

  @override
  Future<void> onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    Map<String, dynamic>? headers = options.headers; // header参数
    Map<String, dynamic> postBodyParam = options.data ?? Map(); //post body接口参数
    Map<String, dynamic> getBodyParm = options.queryParameters; //get body参数

    if (this.isNeedHandler) {
      //如果有凭证，就用凭证
      String? token = await UserBlocTool.getUserAuth();
      if (!SilTools.stringIsEmpty(token)) {
        headers['token'] = token;
        headers['Authorization'] = token;
        headers['Appversion'] = kVersionInfo['version'];
      }

      // 处理公共参数body参数
      // postBodyParam = await getRequestEncryptionParamDictByParamDictType4(
      //     postBodyParam, AppKey);

      // getBodyParm = await getRequestEncryptionParamDictByParamDictType4(
      //     getBodyParm, AppKey);

      // 根据当前语言判断
      LanguageController languageController = LanguageController();
      String? languageStr = languageController.getCurLanguageStr();
      // 判断使用中文还是英文提示
      Map languageApiMap = SilLocalizations.languageApiMap;
      headers['Lang'] = 'en';
      languageApiMap.forEach((key, value) {
        if (languageStr == key) {
          headers['Lang'] = value;
        }
      });
    }

    RequestOptions tempOptions = options;
    tempOptions.headers = headers;
    tempOptions.queryParameters = getBodyParm;
    tempOptions.data = this.isFormData
        ? FormData.fromMap(postBodyParam)
        : postBodyParam; // 处理上传文件
    handler.next(tempOptions);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    handler.next(response);
  }
}
